package com.nl.controller.web.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.mapper.CommonMapper;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.SmsCounty;
import com.nl.controller.web.bean.SmsMgrInfo;
import com.nl.controller.web.bean.SmsMgrTemplateInfo;
import com.nl.controller.web.bean.SmsRule;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.mapper.SmsBusiMapper;
import com.nl.controller.web.mapper.SmsUserMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsUserService {
	@Autowired
	private SmsUserMapper smsUserMapper;
	@Autowired
	private SmsBusiMapper smsBusiMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private CommonMapper commonMapper;

	@SystemServiceLog(description = "根据地市的id查询区县信息", value = false)
	public List<SmsCounty> findCountyByCityId(String cityId) {
		List<SmsCounty> list = new ArrayList<SmsCounty>();
		try {
			list = smsUserMapper.findCountyByCityId(cityId);
			log.info("根据地市的id查询区县信息：" + cityId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据地市的id查询区县信息：" + cityId);
			throw new SmsException("根据地市的id查询区县信息：" + cityId);
		}
		return list;
	}

	public List<SmsUsers> findUserBymsisdn(String msisdn, String name) {
		Map<String, Object> map = new HashMap<>();
		map.put("msisdn", msisdn);
		map.put("userName", name);
		List<SmsUsers> list;
		try {
			list = smsUserMapper.findUser(map);

			commonService.createSmsOperLog("4", "查询用户列表", "0", "用户管理");
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("按照条件查询用户的信息");
			commonService.createSmsOperLog("4", "查询用户列表", "1", "用户管理");
			throw new SmsException("按照条件查询用户的信息");
		}
	}

	public List<SmsUsers> setMgrName(List<SmsUsers> list) {
		for (SmsUsers smsUsers : list) {
			if ("3".equals(smsUsers.getDuty())) {
			String[] mgrIds = smsUsers.getMgrId().split(",");
			StringBuffer sBuffer = new StringBuffer();
			for (String mgrId : mgrIds) {
				SmsMgrInfo smsMgrInfo = smsBusiMapper.findByMgrId(mgrId);
				sBuffer.append(smsMgrInfo.getName() + ",");
			}
			smsUsers.setMgrIdName(sBuffer.toString());
		}
		}
		return list;
	}

	@SystemServiceLog(description = "按照条件查询用户的信息", value = false)
	public PageInfo<SmsUsers> findUser(int page, int limit, String msisdn, String name, String duty, String cityId,
			String countyId, String isCheck) {
		Map<String, Object> map = new HashMap<>();
		map.put("msisdn", msisdn);
		map.put("userName", name);
		map.put("duty", duty);
		map.put("cityId", cityId);
		map.put("countyId", countyId);
		map.put("isCheck", isCheck);
		PageHelper.startPage(page, limit);
		List<SmsUsers> list = new ArrayList<>();
		try {
			list = smsUserMapper.findUser(map);
			for (SmsUsers smsUsers : list) {
				if ((!"25".equals(smsUsers.getCityId())) && (null != smsUsers.getCountyId())
						&& (!"".equals(smsUsers.getCountyId()))) {
					String province = "江苏省" + "/" + smsUsers.getCityName() + "市" + "/" + smsUsers.getCountyName();
					smsUsers.setProvince(province);
				} else if ((!"25".equals(smsUsers.getCityId())) && (null == smsUsers.getCountyId())) {
					String province = "江苏省" + "/" + smsUsers.getCityName() + "市";
					smsUsers.setProvince(province);
				} else {
					String province = "江苏省";
					smsUsers.setProvince(province);
				}

				if ("0".equals(smsUsers.getIsCheck())) {
					smsUsers.setCheckName("是");
				} else if ("1".equals(smsUsers.getIsCheck())) {
					smsUsers.setCheckName("否");
				} else {
					smsUsers.setCheckName("未定义");
				}
			}
			commonService.createSmsOperLog("4", "查询用户列表", "0", "用户管理");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("按照条件查询用户的信息");
			commonService.createSmsOperLog("4", "查询用户列表", "1", "用户管理");
			throw new SmsException("按照条件查询用户的信息");
		}
		// 查询用户的角色信息
		if (list.size() > 0) {
			for (SmsUsers user : list) {
				log.info(user.toString());
				List<SmsRule> roleList = new ArrayList<>();
				try {
					roleList = smsUserMapper.findRuleNameByUserid(user.getUserId());
				} catch (Exception e) {
					e.printStackTrace();
					log.error("获取用户角色");
					throw new SmsException("获取用户角色");
				}
				StringBuffer sbf = new StringBuffer();
				int i = 1;
				if (roleList.size() > 0) {
					for (SmsRule smsRule : roleList) {
						sbf.append(smsRule.getRoleName());
						if (i < roleList.size()) {
							sbf.append(",");
							i++;
						}
					}
					user.setSmsRuleName(sbf.toString());
				}
			}
		}
		PageInfo<SmsUsers> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	@SystemServiceLog(description = "根据区县的id查询项目信息", value = false)
	public List<SmsMgrInfo> findMgrByCountyId(String countyId, String duty, String msisdn) {
		List<SmsMgrInfo> list = new ArrayList<SmsMgrInfo>();
		try {
			list = smsUserMapper.findMgrByCountyId(countyId);
			log.info("根据区县的id查询项目信息：" + countyId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据区县的id查询项目信息：" + countyId);
			throw new SmsException("根据区县的id查询项目信息：" + countyId);
		}
		return list;
	}

	@SystemServiceLog(description = "查询所有角色的信息", value = false)
	public List<SmsRule> findRule(String duty) {
		List<SmsRule> list = new ArrayList<>();
		try {
			list = smsUserMapper.findRule(duty);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询所有角色的信息");
			throw new SmsException("查询所有角色的信息");
		}
		return list;
	}

	@SystemServiceLog(description = "获取用户id", value = false)
	public String findMaxUserId() {
		String userId;
		try {
			userId = smsUserMapper.findMaxUserId();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取用户id");
			throw new SmsException("获取用户id");
		}
		return userId;
	}

	@SystemServiceLog(description = "添加用户", value = false)
	public int addUser(String msisdn, String userName, String password, String duty, String cityId, String mgrId,
			String roleId, String isCheck, String countyId) {
		SmsUsers user = new SmsUsers();
		user.setUserId(findMaxUserId());
		user.setUserName(userName);
		user.setPassword(password);
		user.setDuty(duty);
		user.setCityId(cityId);
		user.setState("0");
		user.setMsisdn(msisdn);
		user.setIsCheck(isCheck);
		user.setCountyId(null == countyId ? "" : countyId);
		if (selectMsisdn(msisdn)) {
			if (mgrId.length() > 0) {
				if (",".equals(String.valueOf(mgrId.charAt(mgrId.length() - 1)))) {
					mgrId = mgrId.substring(0, mgrId.length() - 1);
				}
			}
			user.setMgrId(mgrId);
			if (roleId.length() > 0) {
				if (",".equals(String.valueOf(roleId.charAt(roleId.length() - 1)))) {
					roleId = roleId.substring(0, roleId.length() - 1);
				}
			}
			this.addUserRole(findMaxUserId(), roleId);
		} else {
			return -1;
		}
		int result;
		try {
			result = smsUserMapper.addUser(user);
			commonService.createSmsOperLog("2", "添加用户" + userName, "0", "用户管理");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("添加用户信息：" + user.getUserId());
			commonService.createSmsOperLog("2", "添加用户" + userName, "1", "用户管理");
			throw new SmsException("添加用户信息：" + user.getUserId());
		}
		return result;
	}

	@SystemServiceLog(description = "添加用户和角色的对应关系", value = false)
	public int addUserRole(String userId, String roleId) {
		String[] arr = roleId.split(",");
		int j = 0;
		for (int i = 0; i < arr.length; i++) {
			Map<String, Object> map = new HashMap<>();
			map.put("userId", userId);
			map.put("roleId", arr[i]);
			int result;
			try {
				result = smsUserMapper.addUserRole(map);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("添加用户和角色的对应关系：" + userId);
				throw new SmsException("添加用户和角色的对应关系：" + userId);
			}

			j++;
		}
		return j;
	}

	@SystemServiceLog(description = "根据用户的编号查询用户的信息", value = false)
	public SmsUsers findUserByUserId(String userId) {
		SmsUsers smsUsers = smsUserMapper.findUserByUserId(userId);
		List<SmsRule> roleList = new ArrayList<>();
		try {
			roleList = smsUserMapper.findRuleNameByUserid(smsUsers.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据用户的编号查询用户的信息：" + userId);
			throw new SmsException("根据用户的编号查询用户的信息：" + userId);
		}
		StringBuffer sbf = new StringBuffer();
		int i = 1;
		if (roleList.size() > 0) {
			for (SmsRule smsRule : roleList) {
				sbf.append(smsRule.getRoleId());
				if (i < roleList.size()) {
					sbf.append(",");
					i++;
				}
			}
			smsUsers.setSmsRuleId(sbf.toString());
		}
		return smsUsers;
	}

	@SystemServiceLog(description = "编辑用户的信息", value = false)
	public int modifyUser(String userId, String msisdn, String userName, String password, String duty, String cityId,
			String mgrId, String roleId,String isCheck,String countyId) {
		SmsUsers user = new SmsUsers();
		user.setUserId(userId);
		user.setUserName(userName);
		user.setPassword(password);
		user.setDuty(duty);
		user.setCityId(cityId);
		user.setState("0");
		user.setMsisdn(msisdn);
		user.setCountyId(countyId);
        user.setIsCheck(isCheck);
        SmsUsers userHis = new SmsUsers();//获取修改前数据
        String seqId = commonMapper.getLogSeqId();
		if (mgrId.length() > 0) {
			if (",".equals(String.valueOf(mgrId.charAt(mgrId.length() - 1)))) {
				mgrId = mgrId.substring(0, mgrId.length() - 1);
			}
		}
		user.setMgrId(mgrId);
		if (",".equals(String.valueOf(roleId.charAt(roleId.length() - 1)))) {
			roleId = roleId.substring(0, roleId.length() - 1);
		}
		String[] arr = roleId.split(",");
		this.deleteRoleByuserId(userId);
		this.addUserRole(userId, roleId);
		int result;
		try {	
			userHis = smsUserMapper.findUserByUserId(userId);//获取历史信息
			result = smsUserMapper.modifyUser(user);
			userHis.setSeqId(seqId);
			smsUserMapper.insertHisModifyUser(userHis);
			commonService.createSmsUpdateOperLog("3", "修改用户" + userId, "0", "用户管理", seqId);
		} catch (Exception e) {
 			e.printStackTrace();
			commonService.createSmsUpdateOperLog("3", "修改用户" + userId, "1", "用户管理", seqId);
			log.error("编辑用户的信息：" + userId);
			throw new SmsException("编辑用户信息：" + userId);
		}

		return result;
	}

	@SystemServiceLog(description = "删除用户的角色", value = false)
	public int deleteRoleByuserId(String userId) {
		int result;
		try {
			result = smsUserMapper.deleteRoleByuserId(userId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("删除用户的角色：" + userId);
			throw new SmsException("删除用户的角色：" + userId);
		}
		return result;
	}

	@SystemServiceLog(description = "删除用户", value = false)
	public int deleteUser(String userId, String cityId) {

		if (checkCount(cityId)) {
			return -1;
		}
		int result;
		try {
			result = smsUserMapper.deteteUser(userId);
			this.deleteRoleByuserId(userId);
			commonService.createSmsOperLog("5", "删除用户" + userId, "0", "用户管理");
		} catch (Exception e) {
			e.printStackTrace();
			commonService.createSmsOperLog("5", "删除用户" + userId, "1", "用户管理");
			log.error("删除用户：" + userId);
			throw new SmsException("删除用户：" + userId);
		}
		return result;
	}

	@SystemServiceLog(description = "检验手机号是否重复", value = false)
	public Boolean selectMsisdn(String msisdn) {
		String count;
		try {
			count = smsUserMapper.selectMsisdn(msisdn);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("检验手机号是否重复：" + msisdn);
			throw new SmsException("检验手机号是否重复：" + msisdn);
		}
		return "0".equals(count);
	}

	@SystemServiceLog(description = "根据地市的id查询项目信息", value = false)
	public List<SmsMgrInfo> findMgrByCityId(String cityId, String duty, String msisdn) {
		List<SmsMgrInfo> list = new ArrayList<SmsMgrInfo>();
		try {
			list = smsUserMapper.findMgrByCityId(cityId);
			log.info("根据地市的id查询项目信息：" + cityId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据地市的id查询项目信息：" + cityId);
			throw new SmsException("根据地市的id查询项目信息：" + cityId);
		}
		return list;
	}

	@SystemServiceLog(description = "查询项目管理员的手机号", value = false)
	public List<SmsUsers> getMsisdn(String mgrId) {
		List list;
		try {
			list = smsUserMapper.getMsisdn(mgrId);
			log.error("查询项目管理员的手机号：" + mgrId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询项目管理员的手机号：" + mgrId);
			throw new SmsException("查询项目管理员的手机号：" + mgrId);
		}
		return list;
	}

	@SystemServiceLog(description = "根据城市id查询扩展码信息", value = false)
	public List<String> findExtIdByCityId(String cityId) {
		List list = new ArrayList();
		try {
			list = smsUserMapper.findExtIdByCityId(cityId);
			log.error("根据城市id查询扩展码信息：" + cityId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据城市id查询扩展码信息：" + cityId);
			throw new SmsException("根据城市id查询扩展码信息：" + cityId);
		}
		return list;
	}

	@SystemServiceLog(description = "项目名称联想", value = false)
	public List<SmsMgrInfo> selectMgrNameLike(String key, String cityId,String countyId) {
		List<SmsMgrInfo> list = commonService.selectMgrNameLike(key, cityId, countyId);
		return list;
	}
		
//	@SystemServiceLog(description = "项目名称联想", value = false)
//	public List<SmsMgrInfo> selectMgrNameLikeContent(String key, String mgrId) {
//		List<SmsMgrInfo> list = commonService.selectMgrNameLikeContent(key, mgrId);
//		return list;
//	}

	@SystemServiceLog(description = "查询地市下审核人", value = false)
	public Boolean checkCount(String cityId) {
		String count;
		try {
			count = smsUserMapper.checkCount(cityId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询地市下审核人：" + cityId);
			throw new SmsException("查询地市下审核人：" + cityId);
		}
		if ("1".equals(count)) {
			return true;
		} else {
			return false;
		}
	}
	
	@SystemServiceLog(description = "通过序列号查询用户历史表", value = false)
    public SmsUsers findHisUser(String seqId) {
		SmsUsers smsUsers;
        try {
        	smsUsers = smsUserMapper.findHisUser(seqId);
        /*	if("0".equals(smsUsers.getDuty())){
        		smsUsers.setDutyName("省公司管理员");
        	}else if ("1".equals(smsUsers.getDuty())) {
				smsUsers.setDutyName("地市管理员");
			}else if ("2".equals(smsUsers.getDuty())) {
				smsUsers.setDutyName("区县管理员");
			}else if ("3".equals(smsUsers.getDuty())) {
				smsUsers.setDutyName("项目管理员");
			}*/
        	
        	if("0".equals(smsUsers.getState())){
        		smsUsers.setStateName("正常");
        	}else if ("1".equals(smsUsers.getState())) {
				smsUsers.setStateName("已失效");
			}
        	      	
        	if ("0".equals(smsUsers.getIsCheck())) {
				smsUsers.setCheckName("是");
			} else if ("1".equals(smsUsers.getIsCheck())) {
				smsUsers.setCheckName("否");
			} 
        	;
        	String[] mgrIds = smsUsers.getMgrId().split(",");
			StringBuffer sBuffer = new StringBuffer();
			for (String mgrId : mgrIds) {
				SmsMgrInfo smsMgrInfo = smsBusiMapper.findByMgrId(mgrId);
				sBuffer.append(smsMgrInfo.getName() + ",");
			}
			smsUsers.setMgrIdName(sBuffer.toString());
        	
            commonService.createSmsOperLog("4", "通过序列号查询用户历史表"+ seqId, "0", "日志");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("通过序列号查询用户历史表： " + seqId);
            commonService.createSmsOperLog("4", "通过序列号查询用户历史表"+ seqId, "1", "日志");
            throw new SmsException("查询项目模板表根据项目id： " + seqId);
        }
        return smsUsers;
    }
	
    @SystemServiceLog(description = "根据区县的id查询项目信息", value = false)
    public List<SmsMgrTemplateInfo> findMgrByCountyId(String countyId,String duty,String msisdn,String mgrName) {
        List<SmsMgrTemplateInfo> list = new ArrayList<SmsMgrTemplateInfo>();
        try {
            list = smsUserMapper.findMgrByCountyId(countyId,duty,msisdn,mgrName);
            log.info("根据区县的id查询项目信息：" + countyId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据区县的id查询项目信息：" + countyId);
            throw new SmsException("根据区县的id查询项目信息：" + countyId);
        }
        return list;
    }
    
    @SystemServiceLog(description = "根据地市的id查询项目信息", value = false)
    public List<SmsMgrTemplateInfo> findMgrByCityId(String cityId,String duty,String msisdn,String mgrName) {
        List<SmsMgrTemplateInfo> list = new ArrayList<SmsMgrTemplateInfo>();
        try {
            list = smsUserMapper.findMgrsByCityId(cityId,duty,msisdn,mgrName);
            log.info("根据地市的id查询项目信息：" + cityId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据地市的id查询项目信息：" + cityId);
            throw new SmsException("根据地市的id查询项目信息：" + cityId);
        }
        return list;
    }
    
    @SystemServiceLog(description = "获取项目名称是否存在", value = false)
    public int getMgrName(String mgrName) {
        int flag=0;
        try {
        	 flag = smsUserMapper.getMgrName(mgrName);
             log.info("获取项目名称是否存在：" + flag);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取项目名称是否存在：" + flag);
            throw new SmsException("获取项目名称是否存在：" + flag);
        }
        return flag;
    }
}
